using Admin.NET.Application.Service.CkWarning.Dto;
using Admin.NET.Application.Entity;
using Admin.NET.Core;
using Admin.NET.Core.Service;
using Furion.DependencyInjection;
using SqlSugar;
using Microsoft.AspNetCore.Authorization;

namespace Admin.NET.Application.Service.CkWarning;

/// <summary>
/// 库存预警服务
/// </summary>
[ApiDescriptionSettings("CkWarning", Name = "CkWarning", Order = 100)]
[Route("api/ckWarning")]
[AllowAnonymous]
public class CkWarningService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<GoodsModel> _goodsRep;
    private readonly SqlSugarRepository<GoodsTypeModel> _goodsTypeRep;
    private readonly SqlSugarRepository<WarehouseModel> _warehouseRep;
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly SysDictDataService _sysDictDataService;

    public CkWarningService(
        SqlSugarRepository<GoodsModel> goodsRep,
        SqlSugarRepository<GoodsTypeModel> goodsTypeRep,
        SqlSugarRepository<WarehouseModel> warehouseRep,
        ISqlSugarClient sqlSugarClient,
        SysDictDataService sysDictDataService)
    {
        _goodsRep = goodsRep;
        _goodsTypeRep = goodsTypeRep;
        _warehouseRep = warehouseRep;
        _sqlSugarClient = sqlSugarClient;
        _sysDictDataService = sysDictDataService;
    }

    /// <summary>
    /// 分页查询库存预警信息
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("page")]
    public async Task<SqlSugarPagedList<CkWarningOutput>> Page([FromBody] GetCkWarningInput input)
    {
        try
        {
            // 数据库统计信息
            var goodsCount = await _goodsRep.CountAsync(x => x.IsDelete == false);
            var goodsTypeCount = await _goodsTypeRep.CountAsync(x => x.IsDelete == false);
            var warehouseCount = await _warehouseRep.CountAsync(x => x.IsDelete == false);
            
            Console.WriteLine($"数据库统计 - 货品数量: {goodsCount}, 货品类型数量: {goodsTypeCount}, 仓库数量: {warehouseCount}");

            // 使用简化的查询，只查询货品表和相关表
            var query = _sqlSugarClient.Queryable<GoodsModel>()
                .LeftJoin<GoodsTypeModel>((g, gt) => g.GoodsTypeId == gt.Id)
                .LeftJoin<WarehouseModel>((g, gt, w) => g.GoodsWareId == w.Id)
                .Where(g => g.IsDelete == false)
                .WhereIF(!string.IsNullOrEmpty(input.GoodsKeyword), (g, gt, w) => 
                    g.GoodsName.Contains(input.GoodsKeyword) || g.GoodsCode.Contains(input.GoodsKeyword))
                .WhereIF(!string.IsNullOrEmpty(input.GoodsType), (g, gt, w) => gt.GoodsTypeName.Contains(input.GoodsType))
                .WhereIF(input.CurrentStockMin.HasValue, (g, gt, w) => 50 >= input.CurrentStockMin.Value) // 模拟当前库存50
                .WhereIF(input.CurrentStockMax.HasValue, (g, gt, w) => 50 <= input.CurrentStockMax.Value) // 模拟当前库存50
                .Select((g, gt, w) => new CkWarningOutput
                {
                    Id = g.Id.ToString(),
                    SerialNumber = 0, // 将在后续处理中设置
                    GoodsCode = g.GoodsCode,
                    GoodsName = g.GoodsName,
                    Specs = g.GoodsSpecs != null ? g.GoodsSpecs : "无规格",
                    Unit = g.GoodsUnitId != null ? g.GoodsUnitId.ToString() : "个",
                    GoodsType = gt.GoodsTypeName != null ? gt.GoodsTypeName : "未分类",
                    CurrentStock = 50, // 模拟当前库存
                    StockLowerLimit = 10, // 模拟库存下限
                    StockUpperLimit = 100, // 模拟库存上限
                    BelowLowerLimitPercent = 10.00m, // 模拟低于下限百分比
                    AboveUpperLimitPercent = 10.00m // 模拟高于上限百分比
                })
                .OrderBy(g => g.Id);

            // 生成SQL查询语句用于调试
            var sql = query.ToSql();
            Console.WriteLine($"生成的SQL查询: {sql.Key}");
            Console.WriteLine($"查询参数: {string.Join(", ", sql.Value.Select(p => $"{p.ParameterName}={p.Value}"))}");

            var result = await query.ToPagedListAsync(input.Page, input.PageSize);

            Console.WriteLine($"查询结果 - 总数: {result.Total}, 当前页数据量: {result.Items.Count()}");

            // 设置序号
            var itemsList = result.Items.ToList();
            for (int i = 0; i < itemsList.Count; i++)
            {
                itemsList[i].SerialNumber = (input.Page - 1) * input.PageSize + i + 1;
            }

            // 获取货品单位字典数据（使用与库存查询相同的方式）
            var goodsUnitDict = await _sysDictDataService.GetDataList("GoodsEnumm");
            
            // 映射货品单位名称（完全按照库存查询的逻辑）
            foreach (var item in itemsList)
            {
                if (!string.IsNullOrEmpty(item.Unit))
                {
                    // 按照库存查询的逻辑：优先匹配 value，然后匹配 id
                    var unit = goodsUnitDict?.FirstOrDefault(u => 
                        u.Value == item.Unit || u.Id.ToString() == item.Unit);
                    
                    if (unit != null)
                    {
                        // 按照库存查询的逻辑：优先使用 label，如果没有则使用 name
                        item.Unit = !string.IsNullOrEmpty(unit.Label) ? unit.Label : unit.Name ?? item.Unit;
                    }
                }
            }

            result.Items = itemsList;
            
            Console.WriteLine($"最终返回结果 - 数据项数: {result.Items.Count()}, 总数: {result.Total}");

            return result;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"库存预警查询异常: {ex.Message}");
            Console.WriteLine($"异常堆栈: {ex.StackTrace}");
            throw;
        }
    }

    /// <summary>
    /// 导出库存预警信息
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("export")]
    public async Task<byte[]> Export([FromBody] GetCkWarningInput input)
    {
        try
        {
            // 获取所有数据用于导出
            input.Page = 1;
            input.PageSize = int.MaxValue;
            
            var result = await Page(input);
            
            // 转换为导出格式
            var exportData = result.Items.Select(item => new ExportCkWarningOutput
            {
                GoodsCode = item.GoodsCode,
                GoodsName = item.GoodsName,
                Specs = item.Specs,
                Unit = item.Unit,
                GoodsType = item.GoodsType,
                CurrentStock = item.CurrentStock,
                StockLowerLimit = item.StockLowerLimit,
                StockUpperLimit = item.StockUpperLimit,
                BelowLowerLimitPercent = item.BelowLowerLimitPercent,
                AboveUpperLimitPercent = item.AboveUpperLimitPercent
            }).ToList();

            // 这里应该使用Excel导出库，暂时返回空数组
            return new byte[0];
        }
        catch (Exception ex)
        {
            Console.WriteLine($"导出库存预警信息异常: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// 获取库存预警详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("detail")]
    public async Task<CkWarningOutput> GetDetail([FromQuery] string id)
    {
        var goods = await _goodsRep.GetByIdAsync(id);
        if (goods == null)
        {
            throw new Exception("库存预警信息不存在");
        }

        var goodsType = await _goodsTypeRep.GetByIdAsync(goods.GoodsTypeId);
        var warehouse = await _warehouseRep.GetByIdAsync(goods.GoodsWareId);

        // 获取货品单位字典数据（使用与库存查询相同的方式）
        var goodsUnitDict = await _sysDictDataService.GetDataList("GoodsEnumm");
        var unitValue = goods.GoodsUnitId?.ToString() ?? "个";
        
        // 映射货品单位名称（完全按照库存查询的逻辑）
        if (!string.IsNullOrEmpty(unitValue))
        {
            var unit = goodsUnitDict?.FirstOrDefault(u => 
                u.Value == unitValue || u.Id.ToString() == unitValue);
            
            if (unit != null)
            {
                unitValue = !string.IsNullOrEmpty(unit.Label) ? unit.Label : unit.Name ?? unitValue;
            }
        }

        return new CkWarningOutput
        {
            Id = goods.Id.ToString(),
            SerialNumber = 1,
            GoodsCode = goods.GoodsCode,
            GoodsName = goods.GoodsName,
            Specs = goods.GoodsSpecs ?? "无规格",
            Unit = unitValue,
            GoodsType = goodsType?.GoodsTypeName ?? "未分类",
            CurrentStock = 50, // 模拟当前库存
            StockLowerLimit = 10, // 模拟库存下限
            StockUpperLimit = 100, // 模拟库存上限
            BelowLowerLimitPercent = 10.00m, // 模拟低于下限百分比
            AboveUpperLimitPercent = 10.00m // 模拟高于上限百分比
        };
    }

    /// <summary>
    /// 测试数据库连接
    /// </summary>
    /// <returns></returns>
    [HttpGet("testConnection")]
    public async Task<object> TestConnection()
    {
        try
        {
            var goodsCount = await _goodsRep.CountAsync(x => x.IsDelete == false);
            var goodsTypeCount = await _goodsTypeRep.CountAsync(x => x.IsDelete == false);
            var warehouseCount = await _warehouseRep.CountAsync(x => x.IsDelete == false);

            return new
            {
                success = true,
                message = "数据库连接正常",
                data = new
                {
                    goodsCount,
                    goodsTypeCount,
                    warehouseCount
                }
            };
        }
        catch (Exception ex)
        {
            return new
            {
                success = false,
                message = $"数据库连接失败: {ex.Message}",
                error = ex.ToString()
            };
        }
    }

    /// <summary>
    /// 获取简单货品列表
    /// </summary>
    /// <returns></returns>
    [HttpGet("getSimpleGoodsList")]
    public async Task<object> GetSimpleGoodsList()
    {
        try
        {
            var goodsList = await _goodsRep.GetListAsync(x => x.IsDelete == false);
            
            return new
            {
                success = true,
                message = "获取货品列表成功",
                data = goodsList.Select(g => new
                {
                    id = g.Id,
                    goodsCode = g.GoodsCode,
                    goodsName = g.GoodsName,
                    goodsTypeId = g.GoodsTypeId,
                    goodsSpecs = g.GoodsSpecs,
                    goodsUnitId = g.GoodsUnitId
                }).ToList()
            };
        }
        catch (Exception ex)
        {
            return new
            {
                success = false,
                message = $"获取货品列表失败: {ex.Message}",
                error = ex.ToString()
            };
        }
    }
}
